package liming.ai.core.impl.deepseek;

import liming.ai.data.AbstractRequest;
import liming.ai.data.deepseek.ChatCompletionResponse;
import liming.ai.core.AbstractCore;
import liming.ai.core.ResponseInterface;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

public class DeepSeekCore implements AbstractCore {
    private static final MediaType JSON = MediaType.get("application/json");
    private final OkHttpClient client;
    private final DeepSeekConfig config;
    public DeepSeekCore(DeepSeekConfig config, Interceptor interceptor){
        this.config = config;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(config.getConnectTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(config.getReadTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(config.getWriteTimeout(), TimeUnit.MILLISECONDS);
        if(interceptor!=null)
            builder.addInterceptor(interceptor);
        this.client = builder.build();
    }
    @Override
    public void handle(AbstractRequest request, ResponseInterface responseInterface) {
        Request httpRequest = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .post(RequestBody.create(request.getBody(), JSON))
                .addHeader("Authorization", "Bearer "+config.getApiKey())
                .build();

        client.newCall(httpRequest).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) {
                    responseInterface.onError(request, "请求失败 "+response+" "+ response.body().string());
                    return;
                }

                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.body().byteStream()))) {
                    String line;
                    StringBuilder reasoningContent = new StringBuilder();
                    StringBuilder content = new StringBuilder();

                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String jsonData = line.substring(6);
                            if ("[DONE]".equals(jsonData)) {
                                // 处理完成
                                responseInterface.onComplete(reasoningContent.toString(),content.toString());
                                return;
                            }
                            JSONObject jsonObject = new JSONObject(jsonData);

                            ChatCompletionResponse chunk = ChatCompletionResponse.valueOf(jsonObject);

                            if (chunk.getChoices() != null && !chunk.getChoices().isEmpty()) {
                                ChatCompletionResponse.Delta delta = chunk.getChoice(0).getDelta();
                                if (delta != null) {
                                    String REASONING = delta.getReasoningContent();
                                    if (REASONING != null&& !REASONING.isEmpty()) {
                                        reasoningContent.append(REASONING);
                                        responseInterface.oneReasoningContent(REASONING);
                                    }
                                    String CONTENT = delta.getContent();
                                    if (CONTENT != null && !CONTENT.isEmpty()) {
                                        content.append(CONTENT);
                                        responseInterface.oneContent(CONTENT);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 处理失败
                responseInterface.onError(request,e.getMessage());
            }
        });
        System.out.println("已送达");
    }
}
